<template>
  <div class="article-list">
    <!-- success-text 上滑成功提示 success-duration 上滑等待时间  -->
    <van-pull-refresh
      v-model="isreFreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="加载失败,获取数据错误!!!"
        @load="onLoad"
      >
        <!-- <van-cell
          v-for="(article, index) in list"
          :key="index"
          :title="article.title"
        /> -->
        <ArticleItem
          :article="article"
          v-for="(article, index) in list"
          :key="index"
          :title="article.title"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getUserArticles } from "@/api/article";
import ArticleItem from "../components/article-item.vue";
export default {
  components: {
    ArticleItem,
  },
  data() {
    return {
      list: [], // 存储列表数据的数组
      loading: false, //控制加载中的状态
      finished: false, //控制数据加载中的状态
      timestamp: null, // 请求下一页数据的时间戳
      error: false,
      isreFreshLoading: false, // 控制下拉刷新的 loading 状态
      refreshSuccessText: "刷新成功",
    };
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  methods: {
    async onLoad() {
      try {
        const res = await getUserArticles({
          channel_id: this.channel.id,
          // 初始化List时 无时间戳 传当前时间
          timestamp: this.timestamp || Date.now(),
        });
        // console.log(res);
        // 对results 进行解构
        const { results } = res.data.data;
        this.list.push(...results);
        this.loading = false;
        // 时间戳更改
        if (results.length) {
          this.timestamp = results.pre_timestamp;
        } else {
          // 显示加载完毕
          this.finished = true;
        }
      } catch (error) {
        console.log(error);
        this.error = true;
      }
    },
    // 向下滑动
    async onRefresh() {
      try {
        const res = await getUserArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
        });
        console.log(res);
        // 对results 进行解构
        const { results } = res.data.data;
        this.list.unshift(...results);
        this.isreFreshLoading = false;
      } catch (error) {
        this.refreshSuccessText = "刷新失败";
        this.isreFreshLoading = false;
      }
    },
  },
};
</script>

<style>
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>